<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use fast\Pinyin;
use think\Loader;

/**
 * 车辆信息
 *
 * @icon fa fa-car
 */
class Car extends Backend
{

    /**
     * Car模型对象
     * @var \app\admin\model\Car
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Car;
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['driver'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','license_plate','createtime','IMEI','pinyin']);
                $row->visible(['driver']);
                $row->getRelation('driver')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $pinyin = strtolower(Pinyin::get($params['license_plate'])) ;
            $table_name = config('database.prefix').'car_'.$pinyin;

            $isTable=db()->query('SHOW TABLES LIKE '."'".$table_name."'");
            if($isTable){
                //表存在

            }else {
                //表不存在
                //echo 2;
                $sql = " CREATE TABLE IF NOT EXISTS `$table_name` (
		`id` int(11) NOT NULL AUTO_INCREMENT,
        `IMEI` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '校车终端国际移动设备识别码',
        `CSQ` char(2) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '信号强度0-31',
        `GPS_LNG` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '经度,WGS-84坐标系',
        `GPS_LAT` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '纬度,WGS-84坐标系',
        `SPEED` double DEFAULT NULL COMMENT '速度,来源GPS模块检测,单位km/h',
        `SYS_VER` char(6) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '设备软件版本号',
        `TEMP` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '温度,单位℃',
        `HUM` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '湿度',
        `INIT` tinyint(1) DEFAULT '1' COMMENT '0-服务端下发获取后上报,1-定时主动上报',
        `TIME` int(11) DEFAULT NULL COMMENT '数据采集后上报时的UNIX时间戳',
        `DTIME` date DEFAULT NULL,
        PRIMARY KEY (`id`)
		) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='汽车实时位置';";
                Db::startTrans();
                try{
                    Db::execute($sql);
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->error('数据表创建失败:'.$e->getMessage());
                }

            }
            //$this->model->name='car_'.$pinyin;
            if ($params) {
                $params['pinyin'] = $pinyin;
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $pinyin =strtolower(Pinyin::get($params['license_plate'])) ;
            $table_name = config('database.prefix').'car_'.$pinyin;


            $isTable=db()->query('SHOW TABLES LIKE '."'".$table_name."'");
            if($isTable){
                //表存在

            }else {
                //表不存在
                //echo 2;
                $sql = " CREATE TABLE IF NOT EXISTS `$table_name` (
		`id` int(11) NOT NULL AUTO_INCREMENT,
        `IMEI` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '校车终端国际移动设备识别码',
        `CSQ` char(2) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '信号强度0-31',
        `GPS_LNG` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '经度,WGS-84坐标系',
        `GPS_LAT` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '纬度,WGS-84坐标系',
        `SPEED` double DEFAULT NULL COMMENT '速度,来源GPS模块检测,单位km/h',
        `SYS_VER` char(6) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '设备软件版本号',
        `TEMP` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '温度,单位℃',
        `HUM` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '湿度',
        `INIT` tinyint(1) DEFAULT '1' COMMENT '0-服务端下发获取后上报,1-定时主动上报',
        `TIME` int(11) DEFAULT NULL COMMENT '数据采集后上报时的UNIX时间戳',
        `DTIME` date DEFAULT NULL,
        PRIMARY KEY (`id`)
		) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='汽车实时位置';";
                Db::startTrans();
                try{
                    Db::execute($sql);
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->error('数据表创建失败:'.$e->getMessage());
                }

            }
            if ($params) {
                $params['pinyin'] = $pinyin;
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function selectpage()
    {
        return parent::selectpage(); // TODO: Change the autogenerated stub
    }



    public function detail($IMEI)
    {
        if($IMEI=='')
        {
            $this->error('缺少移动设备识别码');
        }
        $this->assign('IMEI',$IMEI);
        return $this->view->fetch();
    }

    public function setRcDevConfig()
    {
        $params = input('param.');

        $client_id = time().rand();
        $topics_name = "ScBusTem/SetRCDevConfig/".$params['IMEI'];
        $mqtt = $this->connect($client_id);
        $username = 'rl517';                   // set your username
        $password = 'rlian2022';                   // set your password
        if($params['status']==1)
        {
            $params['RC_Pres'] = 0;
        }

        $data = [];
        //$data['IMEI'] = '861714055270312';//状态：1是上车，2是下车
        $data['RC_Type'] = intval($params['status']);//状态：1是上车，2是下车
        $data['RC_Pres'] = intval($params['RC_Pres']);//车上剩余人数 上车时0
        $data['RC_Total'] =intval($params['RC_Total']);//总人数
        //$data['TIME'] = time();//时间戳

        if ($mqtt->connect(true, NULL, $username, $password)) {
            $mqtt->publish($topics_name, json_encode($data), 0, false);
            $mqtt->close();
            echo '成功';exit;
        } else {
            echo '失败';exit;
        }
    }

    public function connect($client_id)
    {
        $server = 'develop.rltest.cn';     // change if necessary
        $port = 1883;                     // change if necessary

        $client_id = $client_id; // make sure this is unique for connecting to sever - you could use uniqid()
        Loader::import('phpMQTT/phpMQTT', EXTEND_PATH);

        $mqtt = new \phpmqtt\phpMQTT($server, $port, $client_id);

        $mqtt->debug = true;
        return $mqtt;
    }

    public function data($id)
    {
        $list = Db::name('circuit')->field('circuit')->select();
        dump($list);exit;
    }

}
